package br.com.carser.util;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;

/**
 * <B>Project: carser-web</B><BR>
 * 
 * Base class for all JSF Managed Beans.
 * 
 * <DL>
 * <DT><B>Created:</B>
 * <DD>Sep 18, 2011</DD></DT>
 * </DL>
 * <DL>
 * <DT><B>Last Modification:</B>
 * <DD>Sep 18, 2011</DD></DT>
 * </DL>
 * 
 * @author Caio Carleto - CarSer - Sep 18, 2011
 * @version 1.0
 */
public abstract class MessageUtil {

	private static ResourceBundle bundle = ResourceBundle.getBundle("resources.messages");

	/**
	 * Add message to current faces context.
	 * 
	 * @param severity FacesMessage.SEVERITY
	 * @param summary key bundle.
	 * @param bundleDetail key bundle.
	 */
	public static void addFacesMessage(final Severity severity,
			final String summary, final String bundleDetail) {
		addMessageToContext(severity,  getString(summary), getString(bundleDetail));
	}
	
	/**
	 * Add message to current faces context.
	 * 
	 * @param severity FacesMessage.SEVERITY
	 * @param summary key bundle.
	 * @param bundleDetail key bundle.
	 */
	public static void addFacesMessage(final Severity severity,
			final String summary, final String bundleDetail, Object... detailParams) {
		String message = getString(bundleDetail, detailParams);
		addMessageToContext(severity,  getString(summary), message);
	}
	
	/**
	 * @return ResourceBundle: resource bundle.
	 */
	public static ResourceBundle getBundle() {
		return bundle;
	}
	
	/**
	 * Looking for a message within resource bundle.
	 * 
	 * @param String
	 *            : key.
	 * @return String: value.
	 */
	public static String getString(String key) {
		String result = "";
		if(key != null) {
			try {
				result =  bundle.getString(key);
			} catch (MissingResourceException e) {
				result = "??? " + key + " ??? not found!";
			}
		}
		return result;
	}
	
	/**
	 * Get message formated with params.
	 * 
	 * @param key
	 * @param params Params to iunclude within message args.
	 * 
	 * @return complete message.
	 */
    public static String getString(String key, Object... params  ) {
    	String result = "";
    	if(key != null) {
            try {
                result = MessageFormat.format(bundle.getString(key), params);
            } catch (MissingResourceException e) {
            	result = '!' + key + '!';
            }
    	}
    	return result;
    }
	
	private static void addMessageToContext(Severity severity, String summary, String detail) {
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(severity, summary, detail));
	}

}